const uploadImage = (dir) => {
  return new Promise((resolve, reject) => {
    let result = {
      filePath: '',
      fileId: ''
    }
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        wx.showLoading({
          title: '上传中',
        })
        const filePath = res.tempFilePaths[0]
        // 上传图片
        const timestamp = new Date().getTime();
        const name = dir ? dir + '/' + timestamp : timestamp
        const cloudPath = `${name}${filePath.match(/\.[^.]+?$/)[0]}`
        wx.cloud.uploadFile({
          cloudPath,
          filePath,
          success: res => {
            // console.log('[上传文件] 成功：', res)
            resolve({
              filePath,
              fileId: res.fileID
            }); //返回成功提示信息
          },
          fail: e => {
            // console.error('[上传文件] 失败：', e)
            wx.showToast({
              icon: 'none',
              title: '上传失败',
            })
            reject(result);
          },
          complete: () => {
            wx.hideLoading()
          }
        })
      },
      fail: e => {
        console.error(e)
        reject(result);
      }
    })
  })
}

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  return `${[year, month, day].map(formatNumber).join('-')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

module.exports = {
  uploadImage,
  formatTime
}